// 头像管理模块
// 使用全局函数（由 core.js 提供）
const { getUserInfo, setUserInfo } = window;
import { showSuccessModal } from './notification-manager.js';

/**
 * 初始化头像修改功能
 */
export function initializeAvatarManager() {
    const changeAvatarBtn = document.getElementById('profile-change-avatar');
    const closeAvatarModalBtn = document.getElementById('close-avatar-modal');
    const avatarModal = document.getElementById('avatar-modal');
    const avatarFileInput = document.getElementById('avatar-upload');
    const avatarUrlInput = document.getElementById('avatar-url');
    const avatarPreview = document.getElementById('avatar-preview');
    const confirmAvatarBtn = document.getElementById('confirm-avatar-btn');
    const resetAvatarBtn = document.getElementById('reset-avatar-btn');
    
    if (!changeAvatarBtn || !closeAvatarModalBtn || !avatarModal || !avatarFileInput || 
        !avatarUrlInput || !avatarPreview || !confirmAvatarBtn || !resetAvatarBtn) return;
    
    // 显示修改头像模态框
    changeAvatarBtn.addEventListener('click', function() {
        // 初始化预览为当前用户头像
        const user = getUserInfo();
        const currentAvatarPreview = document.getElementById('current-avatar-preview');
        if (currentAvatarPreview) {
            if (user && user.avatar) {
                currentAvatarPreview.src = user.avatar;
            } else {
                currentAvatarPreview.src = 'default-avatar.svg';
            }
        }
        
        // 重置输入框
        avatarFileInput.value = '';
        avatarUrlInput.value = '';
        
        // 显示模态框
        avatarModal.classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    });
    
    // 关闭修改头像模态框
    closeAvatarModalBtn.addEventListener('click', function() {
        closeAvatarModal();
    });
    
    // 点击模态框外部关闭
    avatarModal.addEventListener('click', function(e) {
        if (e.target === this) {
            closeAvatarModal();
        }
    });
    
    // 文件上传预览
    avatarFileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件类型
            if (!file.type.match('image.*')) {
                alert('请上传图片文件');
                return;
            }
            
            // 预览图片
            const currentAvatarPreview = document.getElementById('current-avatar-preview');
            const reader = new FileReader();
            reader.onload = function(e) {
                if (currentAvatarPreview) {
                    currentAvatarPreview.src = e.target.result;
                }
                // 清空URL输入框，避免冲突
                avatarUrlInput.value = '';
            };
            reader.readAsDataURL(file);
        }
    });
    
    // URL输入预览
    avatarUrlInput.addEventListener('input', function() {
        const url = this.value.trim();
        const currentAvatarPreview = document.getElementById('current-avatar-preview');
        if (url && currentAvatarPreview) {
            // 尝试设置为预览图，若失败会显示错误
            currentAvatarPreview.src = url;
            currentAvatarPreview.onerror = function() {
                // 图片加载失败时显示提示
                showAvatarError('请输入有效的图片URL');
            };
            currentAvatarPreview.onload = function() {
                // 图片加载成功时清除错误提示
                clearAvatarError();
            };
        }
    });
    
    // 重置头像
    resetAvatarBtn.addEventListener('click', function() {
        const currentAvatarPreview = document.getElementById('current-avatar-preview');
        if (currentAvatarPreview) {
            currentAvatarPreview.src = 'default-avatar.svg';
        }
        avatarFileInput.value = '';
        avatarUrlInput.value = '';
        clearAvatarError();
    });
    
    // 确认修改头像
    confirmAvatarBtn.addEventListener('click', function() {
        handleAvatarUpdate();
    });
}

/**
 * 关闭头像修改模态框
 */
export function closeAvatarModal() {
    const avatarModal = document.getElementById('avatar-modal');
    if (avatarModal) {
        avatarModal.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    }
}

/**
 * 处理头像更新
 */
export function handleAvatarUpdate() {
    const user = getUserInfo();
    if (!user) return;
    
    const avatarPreview = document.getElementById('avatar-preview');
    const avatarErrorEl = document.getElementById('avatar-error');
    
    // 获取新头像URL
    const currentAvatarPreview = document.getElementById('current-avatar-preview');
    const newAvatar = currentAvatarPreview ? currentAvatarPreview.src : '';
    
    // 验证头像URL
    if (!newAvatar || newAvatar === 'about:blank') {
        showAvatarError('请选择有效的头像');
        return;
    }
    
    // 更新用户信息
    const updatedUser = {
        ...user,
        avatar: newAvatar
    };
    
    // 保存更新后的用户信息
    setUserInfo(updatedUser);
    
    // 更新页面显示
    updateAvatarOnPage(newAvatar);
    
    // 关闭模态框
    closeAvatarModal();
    
    // 显示成功提示
    showSuccessModal('头像更新成功', '您的头像已成功更新！');
}

/**
 * 显示头像错误提示
 * @param {string} message 错误信息
 */
export function showAvatarError(message) {
    const avatarErrorEl = document.getElementById('avatar-error');
    if (avatarErrorEl) {
        avatarErrorEl.textContent = message;
        avatarErrorEl.classList.remove('hidden');
    }
}

/**
 * 清除头像错误提示
 */
export function clearAvatarError() {
    const avatarErrorEl = document.getElementById('avatar-error');
    if (avatarErrorEl) {
        avatarErrorEl.classList.add('hidden');
    }
}

/**
 * 更新页面上的头像显示
 * @param {string} avatarUrl 头像URL
 */
export function updateAvatarOnPage(avatarUrl) {
    // 更新用户中心的头像元素
    const avatarImg = document.getElementById('avatar-img');
    if (avatarImg) {
        avatarImg.src = avatarUrl;
    }
    
    // 也更新其他可能的头像元素
    const avatarElements = document.querySelectorAll('.user-avatar img');
    avatarElements.forEach(el => {
        el.src = avatarUrl;
    });
}